package org.example.virtualsensors.entity.model;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import org.example.virtualsensors.entity.EmsItem;
import org.example.virtualsensors.entity.EmsItemgroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

@Component
public class Host {
        @Autowired
        private StringRedisTemplate redisTemplate;
        // todo ip地址测试是192.168.1.1 记得排查
        public EmsItemgroup itemgroup=new EmsItemgroup();
        public List<Sensor> sensors=new ArrayList<>();
        Thread thread_heartbeat;


        String auth_url="http://localhost:58080/gateway/itemGroup/authorization";

        String host_register_url="http://localhost:58080/gateway/itemGroup/register";
        String sensor_register_url="http://localhost:58080/gateway/item/register";
        String heartbeat_url="http://localhost:58080/gateway/itemGroup/heartbeat";
        String sensor_data_report_url="http://localhost:58080/gateway/realtime/upload";
        String sensor_history_data_report_url="http://localhost:58080/gateway//history/upload";
        //1.认证

        public void auth(){
                if(redisTemplate==null) System.out.println("redisTemplate为空");
                String s = HttpUtil.get(auth_url);
        }

        public void registerHost(String url) throws UnsupportedEncodingException {
                //将emsItemgroup对象转换为json字符串并作为参数

                //由于接受方使用gb2312方式解码，
                //但是我们只能使用uft-8编码，
                //字符串转换的过程是gb2312解码
                // g(a)->str  a=g'(str)  u(x)->g'(str)  x=u'(g'(str))
                // str                       u(y)=x   g(x)=str
                //所以只需要对jsongb23解码
                // g(str)
                String jsonStr = JSONUtil.toJsonStr(itemgroup);
                HttpUtil.post(url,jsonStr);
        }
        //2 注册主机
        public void registerHost() throws UnsupportedEncodingException {
                //将emsItemgroup对象转换为json字符串并作为参数

                //由于接受方使用gb2312方式解码，
                //但是我们只能使用uft-8编码，
                //字符串转换的过程是gb2312解码
                // g(a)->str  a=g'(str)  u(x)->g'(str)  x=u'(g'(str))
                // str                       u(y)=x   g(x)=str
                //所以只需要对jsongb23解码
                // g(str)
                String jsonStr = JSONUtil.toJsonStr(itemgroup);
                HttpUtil.post(host_register_url,jsonStr);

                registerSensor();
                heartbeat();
        }
//        注册传感器
        public void registerSensor(){
                for (Sensor sensor : sensors) {
                        sensor.registerSensor();
                }
        }

        //发送心跳

        public void heartbeat(String url){
                if(thread_heartbeat!=null&&thread_heartbeat.isAlive()) {
                        return;
                };
                ItemGroupHeartDto itemGroupHeartDto=new ItemGroupHeartDto();
                itemGroupHeartDto.setItemgroupKey(itemgroup.getItemgroupKey());
                itemGroupHeartDto.setItemgroupModel(itemgroup.getItemgroupModel());
                itemGroupHeartDto.setItemgroupSn(itemgroup.getItemgroupSn());
                itemGroupHeartDto.setItemgroupName(itemgroup.getItemgroupName());
                itemGroupHeartDto.setItemgroupHostIp(itemgroup.getAppAddress());
                itemGroupHeartDto.setMqttclientid(itemgroup.getItemgroupKey());
                thread_heartbeat= new Thread(() -> {
                        while(true){
                                System.out.println("正在发送心跳");
                                String res = HttpUtil.post(url, JSONUtil.toJsonStr(itemGroupHeartDto));
                                System.out.println("发送心跳结果: " + res);
                                try {
                                Thread.sleep(20000);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                });
                thread_heartbeat.start();
        };
        //停止发送心跳
        public void shutdown(){
                if(thread_heartbeat!=null&&thread_heartbeat.isAlive()){
                        thread_heartbeat.stop();// todo 之后再优化
                };
        }
        public void heartbeat(){
                if(thread_heartbeat!=null&&thread_heartbeat.isAlive()) {
                        return;
                };
//        每5秒发送一次心跳

                ItemGroupHeartDto itemGroupHeartDto = new ItemGroupHeartDto();
                itemGroupHeartDto.setItemgroupKey(itemgroup.getItemgroupKey());
                itemGroupHeartDto.setItemgroupModel(itemgroup.getItemgroupModel());
                itemGroupHeartDto.setItemgroupSn(itemgroup.getItemgroupSn());
                itemGroupHeartDto.setItemgroupName(itemgroup.getItemgroupName());
                itemGroupHeartDto.setItemgroupHostIp(itemgroup.getAppAddress());
                itemGroupHeartDto.setMqttclientid(itemgroup.getItemgroupKey());
                thread_heartbeat= new Thread(() -> {
                        try {
                                int i=0;
                                while(i<100) {
                                        i++;
                                        System.out.println("正在发送心跳"+i);
                                        HttpUtil.post(heartbeat_url, JSONUtil.toJsonStr(itemGroupHeartDto));
                                        Thread.sleep(5000);
                                }
                        } catch (InterruptedException e) {
                                e.printStackTrace();
                        }
                });
                thread_heartbeat.start();
        }
}
